<?php
/**
 * 设置分组控制器
 * @author yupoxiong<i@yufuping.com>
 */

namespace app\admin\controller;

use think\db\Query;
use support\Request;
use support\Response;
use think\facade\Cache;
use app\admin\model\AdminMenu;
use app\common\model\SettingGroup;
use think\db\exception\DbException;
use app\common\service\SettingService;
use app\common\validate\SettingGroupValidate;

class SettingGroupController extends AdminBaseController
{
    /**
     * @param Request $request
     * @param SettingGroup $model
     * @return Response
     * @throws DbException
     */
    public function index(Request $request, SettingGroup $model): Response
    {
        $param = $request->all();
        $data  = $model->scope('where', $param)
            ->paginate([
                'list_rows' => $this->admin['admin_list_rows'],
                'var_page'  => 'page',
                'query'     => $request->get()
            ]);

        // 关键词，排序等赋值
        $this->assign($request->get());

        $this->assign([
            'data'  => $data,
            'page'  => $data->render(),
            'total' => $data->total(),
        ]);
        return $this->fetch();
    }

    /**
     * @param Request $request
     * @param SettingGroup $model
     * @param SettingGroupValidate $validate
     * @param SettingService $service
     * @return Response
     */
    public function add(Request $request, SettingGroup $model, SettingGroupValidate $validate, SettingService $service): Response
    {
        if ($request->method() === 'POST') {
            $param = $request->all();

            $check = $validate->scene('add')->check($param);
            if (!$check) {
                return admin_error($validate->getError());
            }

            if (in_array($param['code'], SETTING_CODE_BLACKLIST, false)) {
                return admin_error('代码 ' . $param['code'] . ' 在黑名单内，禁止使用');
            }

            $result1 = $model::create($param);
            $data    = $model->findOrEmpty($result1->id);

            $result2 = true;
            if ($data->auto_create_menu === 1) {
                $result2 = $service->createSettingMenu($data);
            }

            $result3 = true;
            if ($data->auto_create_cache === 1) {
                $result3 = $service->createCache($data);
            }

            $redirect = isset($param['_create']) && (int)$param['_create'] === 1 ? URL_RELOAD : URL_BACK;

            return $result1 && $result2 && $result3 ? admin_success('添加成功', [], $redirect) : admin_error('添加失败');
        }

        return $this->fetch();
    }

    /**
     * @param Request $request
     * @param SettingGroup $model
     * @param SettingService $service
     * @param SettingGroupValidate $validate
     * @return Response
     */
    public function edit(Request $request, SettingGroup $model, SettingService $service, SettingGroupValidate $validate): Response
    {
        $id = $request->input('id');
        /** @var SettingGroup $data */
        $data = $model->findOrEmpty($id);
        if ($request->method() === 'POST') {
            $param = $request->all();

            $check = $validate->scene('edit')->check($param);
            if (!$check) {
                return admin_error($validate->getError());
            }

            $result1 = $data->save($param);
            $data    = $model->findOrEmpty($data->id);

            $result2 = true;
            if ($data->auto_create_menu === 1) {
                $result2 = $service->createSettingMenu($data);
            }

            $result3 = true;
            if ($data->auto_create_cache === 1) {
                $result3 = $service->createCache($data);
            }

            return $result1 && $result2 && $result3 ? admin_success('修改成功', [], URL_BACK) : admin_error('修改失败');
        }

        $this->assign([
            'data' => $data,
        ]);

        return $this->fetch('add');
    }

    /**
     * @param $id
     * @param SettingGroup $model
     * @return Response
     */
    public function del($id, SettingGroup $model): Response
    {
        $check = $model->inNoDeletionIds($id);
        if (false !== $check) {
            return admin_error('ID 为' . $check . '的数据无法删除');
        }
        // 删除限制
        $relation_name    = 'setting';
        $relation_cn_name = '设置';
        $tips             = '下有' . $relation_cn_name . '数据，请删除' . $relation_cn_name . '数据后再进行删除操作';
        if (is_array($id)) {
            foreach ($id as $item) {
                /** @var SettingGroup $data */
                $data = $model->findOrEmpty($item);
                if ($data->$relation_name->count() > 0) {
                    return admin_error($data->name . $tips);
                }
            }
        } else {
            /** @var SettingGroup $data */
            $data = $model->findOrEmpty($id);
            if ($data->$relation_name->count() > 0) {
                return admin_error($data->name . $tips);
            }
        }

        $result = $model::destroy(static function ($query) use ($id) {
            /** @var Query $query */
            $query->whereIn('id', $id);
        });

        return $result ? admin_success('删除成功', [], URL_RELOAD) : admin_error('删除失败');
    }


    /**
     * 生成配置文件，配置文件名为模块名
     * @param Request $request
     * @param SettingGroup $model
     * @param SettingService $service
     * @return Response
     */
    public function cache(Request $request, SettingGroup $model, SettingService $service): Response
    {
        $id = $request->input('id');

        $data = $model->findOrEmpty($id);

        $result = $service->createCache($data);

        return $result ? admin_success('生成成功', [], URL_RELOAD) : admin_error('生成失败');

    }

    /**
     * @param Request $request
     * @param SettingGroup $model
     * @param SettingService $service
     * @return Response
     */
    public function menu(Request $request, SettingGroup $model,SettingService $service): Response
    {
        $id = $request->input('id');

        $data = $model->findOrEmpty($id);
        if ($data->isEmpty()) {
            return admin_error('数据不存在');
        }

        $have    = (new AdminMenu)->where('url', $service->getSettingMenuUrl($data))->findOrEmpty();
        $warning = Cache::has('create_setting_menu_' . $data->code);
        if (!$warning && !$have->isEmpty()) {

            Cache::set('create_setting_menu_' . $data->code, '1', 5);
            return admin_error('当前配置菜单已存在，如果确认要替换请在5秒内再次点击生成按钮');
        }

        $result = $service->createSettingMenu($data);

        return $result ? admin_success('生成成功', [], URL_RELOAD) : admin_error('生成失败');
    }

}
